package com.ktgj.hotel.utils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class CipherUtil {

    public static final String CHARSET = "UTF-8";
    public static final String KEY_DES = "DES";
    static final String CIPHER_DES = "DES/CBC/PKCS5Padding";
    private static final String HEX_CHARS = "0123456789abcdef";

    /**
     * DES对称加密
     * @param content
     * @param password 对称加密的key
     * @return
     * @throws Exception
     */
    public static String desEncrypt(String content,String password) throws Exception{
        SecretKeySpec secretKey=new SecretKeySpec(password.getBytes(CHARSET), KEY_DES);
        Cipher cipher=Cipher.getInstance(CIPHER_DES);
        byte[] byteContent=content.getBytes(CHARSET);
        IvParameterSpec iv=new IvParameterSpec(password.getBytes(CHARSET));
        cipher.init(Cipher.ENCRYPT_MODE, secretKey,iv);
        byte[] result=cipher.doFinal(byteContent);
        return toHexString(result);
    }

    public static String toHexString(byte[] bytes) {
        StringBuilder buffer = new StringBuilder();
        for (byte aByte : bytes) {
            buffer.append(HEX_CHARS.charAt(aByte >>> 4 & 0x0F));
            buffer.append(HEX_CHARS.charAt(aByte & 0x0F));
        }
        return buffer.toString();
    }

    /**
     * DES对称解密
     * @param content
     * @param password 对称加密的key
     * @return
     * @throws Exception
     */
    public static String desDecrypt(String content, String password) throws Exception {
        byte[] bytes = HexUtil.toByteArray(content);
        Cipher cipher = Cipher.getInstance(CIPHER_DES);
        DESKeySpec desKeySpec = new DESKeySpec(password.getBytes(CHARSET));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(KEY_DES);
        SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
        IvParameterSpec iv = new IvParameterSpec(password.getBytes(CHARSET));
        cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
        byte[] retByte = cipher.doFinal(bytes);
        return new String(retByte);
    }
}
